package examples;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Atomic {
    AtomicInteger  i = new AtomicInteger(1);

    public static void main(String[] args) {
        List<Thread> threads = new ArrayList<>();
        AtomicTest test = new AtomicTest();
        for(int i = 0; i < 1000; i++){
            threads.add(new Thread(()->{
                test.decrease(1);
            }));
        }

        threads.forEach(thread -> {
            thread.start();
        });
        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(test.get());

    }
}
class AtomicTest{
    AtomicInteger i = new AtomicInteger(1000);

    void decrease(int amount){
        while(true){
            int pre = i.get();
            int next = pre - amount;
            if(i.compareAndSet(pre, next)) break;
            i.updateAndGet(x->x + amount);
        }
    }

    int get(){
        return i.get();
    }
}


